<?php

namespace app\admin\controller;

use app\models\CampusModel;
use app\models\CompanyModel;
use app\models\RegionalModel;
use app\models\UserModel;

class Campus extends Common
{

    /**
     * @var CompanyModel
     */
    protected $companyModel;

    /**
     * 校区管理模型.
     *
     * @var CampusModel
     */
    protected $campusModel;

	/**
	 * 区域管理模型.
	 *
	 *  @var RegionalModel
	 */
	protected $regionalModel;

	/**
	 * 用户管理模型.
	 *
	 *  @var UserModel
	 */
	protected $userModel;

    /**
     * 校区管理.
     *
     * @throws \think\exception\DbException
     *
     * @return mixed
     */
    public function lists()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $campus = $this->campusModel->getCampusLists($param);
            $this->success('success', '', $campus, 0);
        }
        $type = get_current_type();
        $where = [];
        if($type != 1){ //非超管
            $where['company_id'] = get_current_company_id();
        }
        $regional = $this->regionalModel->where($where)->select();
        return $this->fetch('',['type' => $type, 'regional' => $regional]);
    }

	/**
	 * 添加校区.
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
    public function campus_add()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            $data['company_id'] = RegionalModel::get($data['regional_id'])['company_id'];
            $arr = array(
				'campus_name' => $data['campus_name'],
				'company_id' => $data['company_id'],
				'regional_id' => $data['regional_id'],
			);
            if($this->campusModel->get($arr)){
                $this->error('该校区已经存在', null, '', 1);
            }
            if (false !== $this->campusModel->save($data)) {
				$where = [];
				if(get_current_type() == 1){ //系统用户
                    $where['company_id'] = $data['company_id'];
                }else{
                    $where['company_id'] = get_current_company_id();
                }

				$where['wtype'] = ['in','2,3'];
				$where['regional_id'] = ['like','%'.$data['regional_id'].'%'];
				$arr = $this->userModel->where($where)->select();

				foreach ($arr as $item){
				    if($item['campus_id'] != null && strlen($item['campus_id']) > 0) {
                        $str = $item['campus_id'] . ',' . $this->campusModel->id;
                    }else{
                        $str = $this->campusModel->id;
                    }
					$this->userModel->where(['id'=>$item['id']])->update(['campus_id'=>$str]);
				}

				/************更新session***********/
                $member = UserModel::get(['username' => session('user')['username']]);
                session('user', $member->toArray());
                /********************************************/

                $this->success('添加成功', url('Campus/lists'), '', 1);
            }
            $this->error('添加校区失败', null, '', 1);
        }
        $where = [];
		$where['status'] = 1;
		if(get_current_type() == 2){
			$where['company_id'] = get_current_company_id();
		}else if(get_current_type() == 1){  //超管
            /*************过滤掉未分配系统账号的集团*************/
            $user_result = $this->userModel->where(['wtype' => 2])->select();
            $company_user_arr = [];
            foreach ($user_result as $key => $value){
                $company_user_arr[] = $value['company_id'];
            }
            $company_user_arr = array_unique($company_user_arr);
            $company_user_str = implode(',',$company_user_arr);
            $where['company_id'] = ['in',$company_user_str];
        }


		$regionals = $this->regionalModel->all($where);

		/***********集团**********/
		$company_result = $this->companyModel->select();
		$company_arr =[];
		foreach ($company_result as $key => $value){
            $company_arr[$value['id'].''] = $value['company_name'];
        }
        /*****************************/

        if(get_current_type() == 1){    //超级管理员
            foreach ($regionals as $key => $value){
                $value['regional_name'] =   $value['regional_name'].'【'.$company_arr[$value['company_id'].''].'】';
            }
        }

        return $this->fetch('',['regionals'=>$regionals]);
    }

	/**
	 * 编辑校区.
	 * modify by Small Y
	 *
	 * @return mixed
	 * @throws \think\exception\DbException
	 */
    public function campus_edit()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
			$data['company_id'] = RegionalModel::get($data['regional_id'])['company_id'];
			$this->campusModel->save($data,['id'=>$data['id']]);
            $this->success('编辑成功', url('Campus/lists'), '', 1);
        }
		$where = [];
		$where['status'] = 1;
		if(get_current_type() == 2){
			$where['company_id'] = get_current_company_id();
		}
		$regionals = $this->regionalModel->all($where);
		$campus = $this->campusModel->get(input('id'));
		return $this->fetch('',['regionals'=>$regionals,'campus'=>$campus]);
    }

    /**
     * 删除校区.
     *
     * @return mixed
     */
    public function campus_del()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {

            if (!$this->campusModel->where(['id'=>input('id')])->delete()) {
                $this->error('删除校区失败', null, '', 1);
            }
            $this->success('删除成功', url('Campus/lists'), '', 1);
        }
    }

    /**
     * 更改校区状态.
     *
     * @return mixed
     */
    public function campus_status()
    {
        if ($this->request->isAjax() && $this->request->isPost()) {
            $data = input('post.');
            if($data['status'] == 1){
                $msg = '启用';
            }else{
                $msg = '禁用';
            }
            if (!$this->campusModel->save($data,['id'=>$data['id']])) {
                $this->error($msg.'校区失败', null, '', 1);
            }
            $this->success($msg.'成功', '', '', 1);
        }
    }

    /**
     *  实例化.
     */
    protected function _initialize()
    {
        parent::_initialize();
        $this->campusModel = new CampusModel();
        $this->regionalModel = new RegionalModel();
        $this->userModel = new UserModel();
        $this->companyModel = new CompanyModel();
    }
}
